<template>
    <div class="page_root" :key="queryUpdateFlag" data-page-name="交付风险" data-page-identification="n_9v9w34afzn">
        <a-spin :spinning="pageLoading.loading" :tip="pageLoading.tip">
            <!-- begin vid_nsif73j97u 自定义模板_ml8jsy3ukc -->
            <!--          关闭风险-->
            <a-modal
                v-model:visible="state.closeVisible"
                :title="state.activekey === '项目风险' ? '关闭特大风险' : '关闭风险'"
                width="800px"
                @ok="handleCloseRisk"
                @cancel="cancelCloseRisk"
                :ok-button-props="{ loading: state.closeLoading }"
                destroy-on-close
                :mask-closable="false"
                :keyboard="false"
                centered
            >
                <div class="close-form">
                    <a-form :model="state.closeForm" ref="closeRef">
                        <a-row>
                            <a-col :span="24">
                                <a-form-item
                                    label="风险关闭备注"
                                    :rules="[{ required: true, message: '请输入风险关闭备注', trigger: 'blur' }]"
                                    name="riskRemarks"
                                >
                                    <a-input v-model:value="state.closeForm.riskRemarks" :placeholder="inputHolder" />
                                </a-form-item>
                            </a-col>
                        </a-row>
                    </a-form>
                </div>
            </a-modal>
            <!--          关闭风险-->
            <!--          新建风险-->
            <a-modal
                v-model:visible="state.addVisible"
                title="新增项目风险"
                width="800px"
                @ok="handleSubmitRisk"
                @cancel="cancelAddRisk"
                :ok-button-props="{ loading: state.addLoading }"
                destroy-on-close
                :mask-closable="false"
                :keyboard="false"
                centered
            >
                <div class="risk-form">
                    <a-form :model="state.modalForm" ref="formRef">
                        <a-row>
                            <a-col :span="24">
                                <a-form-item
                                    label="风险描述"
                                    :rules="[{ required: true, message: '请输入风险描述', trigger: 'blur' }]"
                                    name="riskDescription"
                                >
                                    <a-input
                                        v-model:value="state.modalForm.riskDescription"
                                        :placeholder="inputHolder"
                                    />
                                </a-form-item>
                            </a-col>
                            <a-col :span="24">
                                <a-form-item
                                    label="解决方案"
                                    :rules="[{ required: true, message: '请输入解决方案', trigger: 'blur' }]"
                                    name="solution"
                                >
                                    <a-input v-model:value="state.modalForm.solution" :placeholder="inputHolder" />
                                </a-form-item>
                            </a-col>
                        </a-row>
                    </a-form>
                </div>
            </a-modal>
            <!--          新建风险-->
            <div class="risk-body">
                <div class="top-search">
                    <!-- 第一行筛选条件 -->
                    <a-row :gutter="16">
                        <a-col :span="6">
                            <a-form-item label="提交人" :label-col="{ span: 4 }" :wrapper-col="{ span: 20 }">
                                <a-select
                                    :placeholder="selectHolder"
                                    v-model:value="state.filter.submitter"
                                    showSearch
                                    :options="peopleList"
                                    :field-names="{ label: 'label', value: 'value' }"
                                    :filter-option="
                                        (input, option) => {
                                            return option.label.toLowerCase().indexOf(input.toLowerCase()) >= 0
                                        }
                                    "
                                    @focus="getAllJfPeople"
                                />
                            </a-form-item>
                        </a-col>
                        <a-col :span="6">
                            <a-form-item label="风险状态" :label-col="{ span: 5 }" :wrapper-col="{ span: 19 }">
                                <a-select
                                    v-model:value="state.filter.riskState"
                                    placeholder="请选择"
                                    allowClear
                                    :options="[
                                        { label: '存在', value: '存在' },
                                        { label: '已关闭', value: '已关闭' }
                                    ]"
                                    show-search
                                    :filter-option="
                                        (input, option) => {
                                            return option.label.toLowerCase().indexOf(input.toLowerCase()) >= 0
                                        }
                                    "
                                />
                            </a-form-item>
                        </a-col>
                        <a-col :span="6">
                            <a-form-item label="提交日期" :label-col="{ span: 5 }" :wrapper-col="{ span: 19 }">
                                <a-range-picker value-format="YYYY-MM-DD" v-model:value="state.filter.timeQuantum" />
                            </a-form-item>
                        </a-col>
                        <a-col :span="6">
                            <a-space>
                                <a-button type="primary" @click="activeChange">查询</a-button>
                                <a-button @click="resetData" type="primary" ghost>重置</a-button>
                            </a-space>
                        </a-col>
                    </a-row>

                    <!-- 操作按钮 -->
                </div>
                <div class="content">
                    <a-tabs v-model:activeKey="state.activekey" @change="activeChange">
                        <a-tab-pane key="项目风险" tab="项目风险">
                            <div class="table-top">
                                <div class="tip-msg">项目风险</div>

                                <div class="right-btn">
                                    <a-button type="primary" @click="handleAddRisk">新建</a-button>
                                </div>
                            </div>
                            <div class="table-box">
                                <a-table
                                    :columns="columns"
                                    :data-source="state.projectRisikData"
                                    bordered
                                    :scroll="{ y: state.tableHeight }"
                                    :pagination="false"
                                    :loading="state.tableLoading"
                                    @resizeColumn="handleResizeColumn"
                                >
                                    <template #bodyCell="{ record, text, column, index }">
                                        <template v-if="column.dataIndex === 'projectOpration'">
                                            <a-space :size="0">
                                                <a-button
                                                    type="link"
                                                    v-if="record.riskState !== '已关闭'"
                                                    size="small"
                                                    @click="handleShowColse(record)"
                                                    >关闭</a-button
                                                >
                                            </a-space>
                                        </template>
                                    </template>
                                </a-table>
                            </div>
                        </a-tab-pane>
                        <a-tab-pane key="任务风险跟踪" tab="任务风险跟踪" force-render>
                            <div class="table-box">
                                <a-table
                                    :pagination="pagination"
                                    centered
                                    bordered
                                    :columns="taskColumns"
                                    :data-source="state.taskRiskData"
                                    :scroll="{ y: state.tableHeight }"
                                    :loading="state.tableLoading"
                                    @resizeColumn="handleResizeColumn"
                                >
                                    <template #bodyCell="{ record, text, column, index }">
                                        <template v-if="column.dataIndex === 'projectOpration'">
                                            <a-space :size="0">
                                                <a-button
                                                    type="link"
                                                    v-if="record.riskState !== '已关闭'"
                                                    size="small"
                                                    @click="handleShowColse(record)"
                                                    >关闭</a-button
                                                >

                                            </a-space>
                                        </template>
                                    </template>
                                </a-table>
                            </div>
                        </a-tab-pane>
                    </a-tabs>
                </div>
            </div>
            <!-- end vid_nsif73j97u 自定义模板_ml8jsy3ukc -->
        </a-spin>
    </div>
</template>
<script setup lang="tsx">
    import {
        h,
        ref,
        reactive,
        toRaw,
        markRaw,
        watch,
        computed,
        onBeforeMount,
        onMounted,
        onBeforeUnmount,
        onUnmounted,
        onActivated,
        onDeactivated
    } from 'vue'
    import { useRoute, useRouter } from 'vue-router'
    const router = useRouter()
    const route = useRoute()
    import { get, post, put, del, request, requestWithHeaders } from '@/utils/http/Axios'
    import {
        cloneDeep,
        localGet,
        merge,
        getDifferenceArray,
        traversalTreeStructure,
        checkCaseCondition,
        renderStringInTemplate,
        handleBreadcrumbJump,
        throttle,
        permission,
        getComponentParamsValue
    } from '@/utils/index'
    import { isNullOrEmpty, isEmptyArr, isNullOrUnDef, isContained, isArray, isEmpty, isObject } from '@/utils/is'
    import dayjs from 'dayjs'
    import { getPagePcChartsDataSourceConvert } from '@/utils/chart'
    import { message, notification, Modal } from 'ant-design-vue'
    import {
        propertyFormatByNumber,
        propertyFormatByPercentage,
        propertyFormatByDate,
        parseSubFromDataList
    } from '@/utils/format'
    import colorTheme from '@/design/custom-theme.json'
    /*** PUBLISH_EXEGESIS ***
 import UserTableRecords from '@/model/UserTableRecords';
 import { getAppBaseUrl } from '@/utils/index';
 import { sendToken } from "@/hooks/useIframeToken";
 import { useSystemStore } from "@/store/modules/system";
 const systemStore = useSystemStore();
 *** PUBLISH_EXEGESIS ***/

    // 获取传入的流程ID和组件参数
    const props = defineProps({
        'processInstanceId': {
            type: [String, Number, Boolean],
            default: undefined
        },
        'useProjectId': {
            type: [String, Number],
            default: undefined
        },
        activeKey: String,
        refreshCount: Number
    })
    const immediateWatch = (source, callback) => {
        watch(source, callback, { deep: true, immediate: true })
    }

    /* -------------------------- 属性定义 -------------------------- */

    const setTimeOutList = []
    const pageLoading = reactive({
        loading: false,
        tip: undefined
    })
    const authInfo = localGet('app-user-store')

    // 处理校验
    const setSubFormName = (parentInfo, name) => {
        return [parentInfo.parents, parentInfo.cycleIndex, name]
    }

    /* ========================== 属性定义 ========================== */

    /* -------------------------- 元素数据引用 -------------------------- */

    /* ========================== 元素数据引用 ========================== */

    /* -------------------------- 页面数据 -------------------------- */

    /* ========================== 页面数据 ========================== */

    /* -------------------------- 响应 -------------------------- */

    /* ========================== 响应 ========================== */

    /* -------------------------- 函数 -------------------------- */

    /* ========================== 函数 ========================== */

    /* -------------------------- 页面参数 -------------------------- */

    const pageParameter_state = reactive({
        'processInstanceId': props.processInstanceId ?? route.query.processInstanceId
    })

    /* ========================== 页面参数 ========================== */

    /* -------------------------- 组件事件处理方法 -------------------------- */

    // ---------------------------- 组件数据同步 ----------------------------

    // ============================ 组件数据同步 ============================

    /* ========================== 组件事件处理方法 ========================== */

    /* -------------------------- 生命周期 -------------------------- */
    // 用于参数变更后重新执行自定义指令
    const queryUpdateFlag = ref(0)
    onMounted(() => {})

    onUnmounted(() => {
        // 销毁定时器
        setTimeOutList.forEach(({ repeat, timer }) => {
            repeat ? clearInterval(timer) : clearTimeout(timer)
        })
    })

    /* ========================== 生命周期 ========================== */

    /* -------------------------- 数据关联处理 -------------------------- */

    /* -------------------------- 表单数据同步 -------------------------- */
    /* ========================== 表单数据同步 ========================== */

    /* ========================== 数据关联处理 ========================== */

    /* -------------------------- 不同组件自定义的处理逻辑 -------------------------- */

    /* ========================== 不同组件自定义的处理逻辑 ========================== */

    // ================================定制化逻辑========================================
    const currentRiskData = ref({})
    const pagination = ref({
        current: 1,
        pageSize: 10,
        showSizeChanger: true,
        total: 0,
        pageSizeOptions: ['10', '20', '40', '60', '80', '100'],
        showTotal: total =>
            `共 ${total} 个项目 第 ${pagination.value.current}/${Math.ceil(total / pagination.value.pageSize)}页`
    })
    const state = reactive({
        filter: {
            projectId: undefined,
            riskState: undefined,
            submitter: undefined,
            timeQuantum: []
        },
        tableLoading: false,
        projectRisikData: [],
        taskRiskData: [],
        modalForm: {
            projectId: undefined,
            riskDescription: undefined,
            solution: undefined
        },
        addVisible: false,
        closeVisible: false,
        addLoading: false,
        closeLoading: false,
        activekey: '项目风险',
        closeForm: {
            projectId: undefined,
            riskId: undefined,
            riskRemarks: undefined,
            dailyItemId: undefined
        },
        tableHeight: 400
    })
    const selectHolder = '请选择'
    const inputHolder = '请输入'
    const headerOffset = ref(210)
    const calcTableHeight = () => {
        state.tableHeight = window.innerHeight - 180 - headerOffset.value
    }
    onMounted(() => {
        calcTableHeight()
        window.addEventListener('resize', calcTableHeight)
    })
    onBeforeUnmount(() => {
        window.removeEventListener('resize', calcTableHeight)
    })
    watch(
        () => [props.useProjectId, props.activeKey, props.refreshCount],
        val => {
            activeChange()
        },
        { immediate: true }
    )
    function activeChange() {
        if (state.activekey === '项目风险') {
            getProjectData()
        } else {
            getTaskData(true)
        }
    }
    const columns = ref([
        {
            dataIndex: 'riskDescription',
            title: '风险描述',
            ellipsis: true,
            align: 'center',
            width: '400px',
            resizable: true
        },
        {
            dataIndex: 'solution',
            title: '解决方案',
            ellipsis: true,
            align: 'center',
            width: '400px',
            resizable: true
        },
        {
            dataIndex: 'riskState',
            title: '风险状态',
            ellipsis: true,
            align: 'center',
            width: '100px',
            resizable: true
        },
        {
            dataIndex: 'approvalStatus',
            title: '审批状态',
            ellipsis: true,
            align: 'center',
            width: '100px',
            resizable: true
        },
        {
            dataIndex: 'submitter',
            title: '提交人',
            ellipsis: true,
            align: 'center',
            width: '100px',
            resizable: true
        },
        {
            dataIndex: 'submissionTime',
            title: '提交时间',
            ellipsis: true,
            align: 'center',
            width: '180px',
            resizable: true
        },
        {
            dataIndex: 'solver',
            title: '解决人',
            ellipsis: true,
            align: 'center',
            width: '180px',
            resizable: true
        },
        {
            dataIndex: 'riskRemarks',
            title: '风险关闭备注',
            ellipsis: true,
            align: 'center',
            width: '200px',
            resizable: true
        },

        {
            dataIndex: 'projectOpration',
            title: '操作',
            align: 'center',
            width: 150,
            fixed: 'right'
        }
    ])
    const taskColumns = ref([
        {
            dataIndex: 'milepostName',
            title: '项目阶段',
            ellipsis: true,
            align: 'center',
            width: '150px',
            resizable: true
        },
        {
            dataIndex: 'taskName',
            title: '任务',
            ellipsis: true,
            align: 'center',
            width: '150px',
            resizable: true
        },
        {
            dataIndex: 'riskDescription',
            title: '风险描述',
            ellipsis: true,
            align: 'center',
            width: '300px',
            resizable: true
        },
        {
            dataIndex: 'solution',
            title: '解决方案',
            ellipsis: true,
            align: 'center',
            width: '300px',
            resizable: true
        },
        {
            dataIndex: 'riskState',
            title: '风险状态',
            ellipsis: true,
            align: 'center',
            width: '100px',
            resizable: true
        },
        {
            dataIndex: 'reportedBy',
            title: '提交人',
            ellipsis: true,
            align: 'center',
            width: '100px',
            resizable: true
        },
        {
            dataIndex: 'dailyDate',
            title: '提交时间',
            ellipsis: true,
            align: 'center',
            width: '180px',
            resizable: true
        },

        {
            dataIndex: 'riskRemarks',
            title: '风险关闭备注',
            ellipsis: true,
            align: 'center',
            width: '200px',
            resizable: true
        },

        {
            dataIndex: 'projectOpration',
            title: '操作',
            align: 'center',
            width: 150,
            fixed: 'right'
        }
    ])
    const peopleList = ref([])
    function getAllJfPeople() {
        get('/solution-ppm/api/v2/built-in-system-ppm/pmgf/get/allUser').then(({ data }) => {
            peopleList.value = data.userDtoList.map(item => {
                return {
                    label: item.name,
                    value: item.name
                }
            })
        })
    }
    function getProjectData() {
        state.tableLoading = true
        post('/solution-ppm/api/v2/built-in-system-ppm/v2/risk/queryRisk', {
            ...state.filter,
            projectId: props.useProjectId
        })
            .then(data => {
                if (data.code !== 200) {
                    message.error(data.message)
                    state.projectRisikData = []
                    return
                }
                state.projectRisikData = data.data.dataList
            })
            .finally(() => {
                state.tableLoading = false
            })
    }
    function getTaskData(flag) {
        state.tableLoading = true
        if (flag) {
            pagination.value.current = 1
        }
        post('/solution-ppm/api/v2/built-in-system-ppm/daily/queryProjectRiskList', {
            ...state.filter,
          reportedBy:state.filter.submitter,
            projectId: props.useProjectId,
            pageNo: pagination.value.current,
            pageSize: pagination.value.pageSize,
            riskState: state.filter.riskState
        })
            .then(data => {
                state.taskRiskData = data.dataList || []
            })
            .finally(() => {
                state.tableLoading = false
            })
    }
    function resetData() {
        state.filter = {
            projectId: undefined,
            riskState: undefined,
            submitter: undefined,
            timeQuantum: []
        }
        pagination.value.current = 1
        pagination.value.pageSize = 10
        activeChange()
    }
    const pageSizeChange = (current, size) => {
        pagination.value.current = current
        pagination.value.pageSize = size
        activeChange()
    }
    const pageChange = (page, pageSize) => {
        pagination.value.current = page
        pagination.value.pageSize = pageSize
        activeChange()
    }

    const formRef = ref(null)
    const closeRef = ref(null)
    function handleAddRisk() {
        state.addVisible = true
        currentRiskData.value = {}
    }
    function handleShowColse(record) {
        console.log(record)
        currentRiskData.value = record
        state.closeVisible = true
        state.closeForm.riskId = record.riskId
        state.closeForm.dailyItemId = record.dailyItemId
    }
    function handleCloseRisk() {
        closeRef.value.validate().then(() => {
            state.addLoading = true
            const api =
                state.activekey === '项目风险'
                    ? '/solution-ppm/api/v2/built-in-system-ppm/v2/risk/updateRisk'
                    : '/solution-ppm/api/v2/built-in-system-ppm/daily/updateRiskState'
            post(api, {
                ...state.closeForm,
                projectId: props.useProjectId
            })
                .then(data => {
                    if (data.code !== 200) {
                        message.error(data.message)
                        return
                    }
                    message.success(data.message)
                    cancelCloseRisk()
                })
                .finally(() => {
                    state.addLoading = false
                })
        })
    }
    function handleSubmitRisk() {
        formRef.value.validate().then(() => {
            state.addLoading = true
            post('/solution-ppm/api/v2/built-in-system-ppm/v2/risk/creatRisk', {
                ...state.modalForm,
                projectId: props.useProjectId
            })
                .then(data => {
                    console.log(data)
                    if (data.code !== 200) {
                        message.error(data.message)
                        return
                    }
                    message.success(data.message)
                    cancelAddRisk()
                })
                .finally(() => {
                    state.addLoading = false
                })
        })
    }
    function cancelAddRisk() {
        currentRiskData.value = {}
        state.addVisible = false
        state.modalForm = {
            projectId: undefined,
            riskDescription: undefined,
            solution: undefined
        }
        activeChange()
    }
    function cancelCloseRisk() {
        currentRiskData.value = {}
        state.closeVisible = false
        state.closeForm = {
            projectId: undefined,
            riskId: undefined,
            riskRemarks: undefined,
            dailyItemId: undefined
        }
        activeChange()
    }
    function handleDeleteRisk(record) {
        post('/solution-ppm/api/v2/built-in-system-ppm/v2/risk/updateRisk', {
            delFlag: 1,
            riskId: record.riskId,
            dailyItemId: record.dailyItemId
        }).then(data => {
            if (data.code !== 200) {
                message.error(data.message)
                return
            }
            message.success(data.message)
            activeChange()
        })
    }
    function handleResizeColumn(w, col) {
        col.width = w
    }
</script>
<style lang="less" scoped>
    .page_root {
        width: 100%;
        height: 100%;
        overflow: auto;
    }
    .page_root :deep(.@{ant-prefix}-spin-nested-loading),
    .page_root :deep(.@{ant-prefix}-spin-container) {
        height: 100%;
    }
    .page_root :deep(.@{ant-prefix}-spin-container .@{ant-prefix}-table-wrapper) {
        display: flex;
        flex-flow: column nowrap;
        justify-content: flex-start;
    }
    .page_root :deep(.@{ant-prefix}-table) {
        flex: auto;
        overflow: auto;
    }
    .table-moreBtn_down {
        overflow: hidden;
        white-space: nowrap;
        text-overflow: ellipsis;
        width: 100px;
    }

    .table-moreBtn_menu :deep(.table-moreBtn_menu-item):hover {
        background: #ebf1ff;
    }

    /*  表格树结构样式处理，展开按钮层级增加*/
    :deep(.@{ant-prefix}-table-row-expand-icon) {
        z-index: 1;
    }
    /*  表格树结构 由于每个表格项采用自定义组件，使用绝对定位布局，开启树结构导致显示异常，暂时使用层级定位位置 */
    :deep(.@{ant-prefix}-table-row-level-1 .@{ant-prefix}-table-cell-with-append .cell-wrapper-left) {
        left: 15px !important;
        width: calc(100% - 15px);
    }
    :deep(.@{ant-prefix}-table-row-level-2 .@{ant-prefix}-table-cell-with-append .cell-wrapper-left) {
        left: 30px !important;
        width: calc(100% - 30px);
    }
    :deep(.@{ant-prefix}-table-row-level-3 .@{ant-prefix}-table-cell-with-append .cell-wrapper-left) {
        left: 45px !important;
        width: calc(100% - 45px);
    }
    :deep(.@{ant-prefix}-table-row-level-4 .@{ant-prefix}-table-cell-with-append .cell-wrapper-left) {
        left: 60px !important;
        width: calc(100% - 60px);
    }

    /* 穿梭框改变默认样式，为根据组件样式控制左右栏宽度。 */
    :deep(.@{ant-prefix}-transfer-list) {
        height: 100%;
        width: 50%;
    }
    /*样式*/
    .top-search {
        background-color: #fff;
        margin-top: 10px;
    }
    .top-search :deep(.ant3-row) {
        height: 40px;
    }
    .top-search :deep(.ant3-col) {
        height: 40px;
    }
    .table-top {
        display: flex;
        justify-content: space-between;
        margin-bottom: 16px;
        align-items: center;
    }
    .tip-msg {
        padding-left: 8px;
        border-left: 4px solid #3875ff;
        height: 16px;
        font-size: 16px;
        font-weight: 600;
        line-height: 16px;
    }
    .right-btn {
        display: flex;
        gap: 8px;
    }
    .table-box :deep(.@{ant-prefix}-table-tbody) tr > td {
        font-size: 14px;
        font-weight: 400;
        color: #262626;
        border-bottom: 1px solid #d9d9d9;
        padding: 8px 16px;
        word-break: break-all;
    }
    /*样式*/
</style>
